package com.lili.collection.core.holder;

import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 *描述: 一个线程只能获取一个连接
 *@date:2023/4/21  16:58
 *@author:lili
 */
@Slf4j
public class PluginConnectionHolder {
    private static final ThreadLocal<Connection> connectionThreadLocal = new ThreadLocal<>();

    /**
     * 获取线程单连接
     * @param dataSource 数据源
     * @return
     * @throws SQLException
     */
    public static Connection getConnection(DataSource dataSource){
        try {
            Connection connection = connectionThreadLocal.get();
            if(connection!=null && !connection.isClosed()){
                return connection;
            }
            synchronized (Thread.currentThread()){
                Connection doubleCheckConnection = connectionThreadLocal.get();
                if(doubleCheckConnection!=null){
                    return doubleCheckConnection;
                }
                connection = dataSource.getConnection();
                connection.setAutoCommit(false);
                connectionThreadLocal.set(connection);
                return connection;
            }
        } catch (Exception e) {
            log.error("获取连接错误!",e);
            throw new RuntimeException(e);
        }
    }
}